﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;

namespace WhileAwayWpf
{
    /// <summary>
    /// Interaction logic for MessageLogUserControl.xaml
    /// </summary>
    public partial class MessageLogUserControl : UserControl
    {
        private EventWaitHandle settingsEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "C4F-WhileAway-Settings");
        private Storyboard glowStoryboardMessage, glowStoryboardName;
        AwayMessageCollection messages = new AwayMessageCollection();
        private AwayMessage currentMessage = new AwayMessage();

        public MessageLogUserControl()
        {
            InitializeComponent();
            messages.LoadFromDisk();
            listBoxMessages.ItemsSource = messages;

            glowStoryboardMessage = (Storyboard)this.Resources["GlowStoryboardMessage"];
            glowStoryboardName = (Storyboard)this.Resources["GlowStoryboardName"];

            stackPanel1.DataContext = currentMessage;
        }

        public AwayMessageCollection Messages
        {
            get { return messages; }
        }

        private void buttonLeaveMessage_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(currentMessage.Sender))
            {
                textBoxName.Focus();
                glowStoryboardName.Begin(textBoxName);
                return;
            }

            if (string.IsNullOrEmpty(currentMessage.Message))
            {
                textBoxMessage.Focus();
                glowStoryboardMessage.Begin(textBoxMessage);
                return;
            }

            LeaveMessage();
        }

        private void LeaveMessage()
        {
            currentMessage.When = DateTime.Now;

            messages.Add(currentMessage);
            messages.Save();

            System.Diagnostics.Process.Start(System.Reflection.Assembly.GetEntryAssembly().CodeBase, "/c");
            settingsEvent.Set();

            // Bind to a new instance to be ready for the next message
            currentMessage = new AwayMessage();
            stackPanel1.DataContext = currentMessage;
        }

        private void UserControl_Unloaded(object sender, RoutedEventArgs e)
        {
            settingsEvent.Set();
        }
    }


}
